package com.ruoyi.system.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DefaultZeroValueUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.BdmBalanceChange;
import com.ruoyi.system.domain.BdmBalanceRechargeRecord;
import com.ruoyi.system.domain.BdmUser;
import com.ruoyi.system.enums.BdmBalanceChangeEnum;
import com.ruoyi.system.enums.BdmBalanceRechargeRecordEnum;
import com.ruoyi.system.mapper.BdmBalanceRechargeRecordMapper;
import com.ruoyi.system.service.IBdmBalanceChangeService;
import com.ruoyi.system.service.IBdmBalanceRechargeRecordService;
import com.ruoyi.system.service.IBdmPayService;
import com.ruoyi.system.service.IBdmUserService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 余额充值记录Service业务层处理
 *
 * @author ruoyi
 * @date 2025-02-26
 */
@Service
public class BdmBalanceRechargeRecordServiceImpl extends ServiceImpl<BdmBalanceRechargeRecordMapper,BdmBalanceRechargeRecord> implements IBdmBalanceRechargeRecordService
{
    @Autowired
    private BdmBalanceRechargeRecordMapper bdmBalanceRechargeRecordMapper;

    @Autowired
    private IBdmPayService bdmPayService;

   @Autowired
    private IBdmBalanceChangeService  bdmBalanceChangeService;

   @Autowired
    private IBdmUserService bdmUserService;

    /**
     * 查询余额充值记录
     *
     * @param id 余额充值记录主键
     * @return 余额充值记录
     */
    @Override
    public BdmBalanceRechargeRecord selectBdmBalanceRechargeRecordById(Long id)
    {
        return bdmBalanceRechargeRecordMapper.selectBdmBalanceRechargeRecordById(id);
    }

    /**
     * 查询余额充值记录列表
     *
     * @param bdmBalanceRechargeRecord 余额充值记录
     * @return 余额充值记录
     */
    @Override
    public List<BdmBalanceRechargeRecord> selectBdmBalanceRechargeRecordList(BdmBalanceRechargeRecord bdmBalanceRechargeRecord)
    {

        bdmBalanceRechargeRecord.setUserId(SecurityUtils.getUserId());
        return bdmBalanceRechargeRecordMapper.selectBdmBalanceRechargeRecordList(bdmBalanceRechargeRecord);
    }

    /**
     * 新增余额充值记录
     *
     * @param bdmBalanceRechargeRecord 余额充值记录
     * @return 结果
     */
    @Override
    public String insertBdmBalanceRechargeRecord(BdmBalanceRechargeRecord bdmBalanceRechargeRecord)
    {
        Long userId = SecurityUtils.getUserId();
        String balanceOrderId = IdUtil.simpleUUID();
        bdmBalanceRechargeRecord.setBalanceOrderId(balanceOrderId);
        bdmBalanceRechargeRecord.setUserId(userId);
        bdmBalanceRechargeRecord.setCreateUser(userId.toString());
        bdmBalanceRechargeRecord.setCreateTime(DateUtils.getNowDate());
        bdmBalanceRechargeRecord.setPayTime(DateUtils.getNowDate());
        bdmBalanceRechargeRecord.setPayState(BdmBalanceRechargeRecordEnum.UNPAID.getType());
        bdmBalanceRechargeRecordMapper.insertBdmBalanceRechargeRecord(bdmBalanceRechargeRecord);
        return balanceOrderId;
    }

    /**
     * 修改余额充值记录
     *
     * @param bdmBalanceRechargeRecord 余额充值记录
     * @return 结果
     */
    @Override
    @Transactional
    public int updateBdmBalanceRechargeRecord(BdmBalanceRechargeRecord bdmBalanceRechargeRecord)
    {
        Date nowDate = DateUtils.getNowDate();
        SysUser user = SecurityUtils.getLoginUser().getUser();

        BdmBalanceRechargeRecord one = this.lambdaQuery().eq(BdmBalanceRechargeRecord::getBalanceOrderId, bdmBalanceRechargeRecord.getBalanceOrderId()).one();

        if (ObjectUtils.isEmpty(one)){
            throw new RuntimeException("订单不存在");
        }

        //修改订单状态
        one.setPayState(BdmBalanceRechargeRecordEnum.HAVE_PAID.getType());
        one.setUpdateTime(nowDate);
        one.setUpdateUser(SecurityUtils.getUserId().toString());
        one.setPayTime(nowDate);

        //查询是否支付
        bdmPayService.selectPay(one);

        int i = bdmBalanceRechargeRecordMapper.updateBdmBalanceRechargeRecord(one);
        if (i==0){
            throw new RuntimeException("修改余额充值订单状态失败");
        }


        BdmUser bdmUser = bdmUserService.lambdaQuery().eq(BdmUser::getSysUserid, user.getUserId()).one();

        //余额
        BigDecimal remainingSum = DefaultZeroValueUtil.getValue(bdmUser.getRemainingSum());
        //积分
        BigDecimal creditScore = new BigDecimal(DefaultZeroValueUtil.getValue(bdmUser.getCreditScore()));


        //记录余额变动表
        BdmBalanceChange bdmBalanceChange = BdmBalanceChange.getBdmBalanceChange(user.getUserId(),
                one.getBalanceOrderId(),
                String.valueOf(one.getMoney()),
                remainingSum.toString(),
                remainingSum.add(one.getMoney()).toString(),
                Long.parseLong(BdmBalanceChangeEnum.BALANCE.getType()),
                Long.parseLong(BdmBalanceChangeEnum.ADD.getType()),
                BdmBalanceChangeEnum.USERS_RECHARGE_THE_BALANCE.getDescription()
        );
        boolean save = bdmBalanceChangeService.save(bdmBalanceChange);
        if (!save){
            throw new RuntimeException("记录余额变动失败");
        }
        //修改用户余额
        bdmUser.setRemainingSum(remainingSum.add(one.getMoney()));
        //记录积分变动表
        BdmBalanceChange bdmBalanceChangeNew = BdmBalanceChange.getBdmBalanceChange(user.getUserId(),
                one.getBalanceOrderId(),
                String.valueOf(one.getIntegral()),
                creditScore.toString(),
                creditScore.add(new BigDecimal(one.getIntegral())).toString(),
                Long.parseLong(BdmBalanceChangeEnum.INTEGRAL.getType()),
                Long.parseLong(BdmBalanceChangeEnum.ADD.getType()),
                BdmBalanceChangeEnum.RECHARGE_BALANCE_AND_GET_BONUS_POINTS.getDescription()
        );
        boolean save1 = bdmBalanceChangeService.save(bdmBalanceChangeNew);

        if (!save1){
            throw new RuntimeException("记录积分变动失败");
        }

        //修改用户积分
        bdmUser.setCreditScore(creditScore.add(new BigDecimal(bdmBalanceRechargeRecord.getIntegral())).toString());

        boolean save2 = bdmUserService.saveOrUpdate(bdmUser);
        if (!save2){
            throw new RuntimeException("用户充值余额失败");
        }

        return i;
    }

    /**
     * 批量删除余额充值记录
     *
     * @param ids 需要删除的余额充值记录主键
     * @return 结果
     */
    @Override
    public int deleteBdmBalanceRechargeRecordByIds(Long[] ids)
    {
        return bdmBalanceRechargeRecordMapper.deleteBdmBalanceRechargeRecordByIds(ids);
    }

    /**
     * 删除余额充值记录信息
     *
     * @param id 余额充值记录主键
     * @return 结果
     */
    @Override
    public int deleteBdmBalanceRechargeRecordById(Long id)
    {
        return bdmBalanceRechargeRecordMapper.deleteBdmBalanceRechargeRecordById(id);
    }
}
